package java6681.generic;

import java.util.*;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;

/**
 * @author Junichiro
 * @description 改进：统计字符串中每个字符出现的次数
 * @date 2021-04-10 21:35
 **/

/*aababcabcdabcdebb*/
public class Counter6681 {
    public static void main(String[] args) {
        /*定义一个字符串*/
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入一个字符串：");
        String line = sc.nextLine();
        count6681(line).forEach(Counter6681::print);
    }

    private static List<Map.Entry<Character, Integer>> count6681(String str) {
        /*定义一个TreeMap集合*/
        TreeMap<Character, Integer> tm = new TreeMap<>();
        /*把字符串转换为字符数组*/
        char[] chs = str.toCharArray();

        for (char c : chs) {
            tm.compute(c, Counter6681::add);
        }
        List<Map.Entry<Character, Integer>> list = new ArrayList<>(tm.entrySet());

        Collections.sort(list, new Comparator<Map.Entry<Character, Integer>>() {
            @Override
            public int compare(Map.Entry<Character, Integer> o1, Map.Entry<Character, Integer> o2) {
                int num = o2.getValue() - o1.getValue();
                int num2 = num == 0 ? o1.getKey() - o2.getKey() : num;
                return num2;
            }
        });
        return list;
    }

    private static Integer add(Character key, Integer value) {
        return value == null ? 1 : value + 1;
    }

    private static void print(Map.Entry<Character, Integer> charIntEntry) {
        System.out.println(charIntEntry.getKey() + "出现" + charIntEntry.getValue() + "次");
    }
}
